﻿using Application.Utils;
using Infrastructure.Extension;
using Infrastructure.WebApi;
using IP2Region.Net.XDB;
using System.Text.RegularExpressions;

namespace Application.Service
{
    public class LogService : ILogService
    {
        public JobManagerDbContext _context { get; set; }
        private readonly ISearcher _searcher;
        private readonly Accessor _accessor;
        public LogService(JobManagerDbContext DbContext, ISearcher _searcher, Accessor accessor)
        {
            _context = DbContext;
            this._searcher = _searcher;
            _accessor = accessor;
        }
        public async Task<Page<SysLogOperation>> Get(KeywordRequest request)
        {
            request.StringTrim();
            var data = await _context.SysLogOperation.OrderByDescending(s => s.CreateTime).AsQueryable()
                .WhereIf(request.Keyword.Has(), s => s.Title.StartsWith(request.Keyword))
                .WhereIf(_accessor.RoleKey == GlobalData.Role.UserRoleKey, s => s.OperatorId == _accessor.ManagerId)
                .PageAsync(request.PageIndex, request.PageSize);
            return data;
        }
        public async Task Post(SysLogOperation request)
        {
            try
            {
                if (Regex.IsMatch(request.Ip, @"\b(?:\d{1,3}\.){3}\d{1,3}\b"))
                {
                    var region = _searcher.Search(request.Ip);//国家|区域|省份|城市|ISP：中国|0|上海|上海市|电信
                    var arr = region.Split('|');
                    if (arr[0] == "中国")
                    {
                        request.Region = arr[3];
                    }
                    else
                    {
                        request.Region = $"{arr[0]}·{arr[3]}";
                    }
                }
            }
            catch
            {
            }
            await _context.SysLogOperation.AddAsync(request);
            await _context.SaveChangesAsync();
        }
    }

    public interface ILogService
    {
        Task<Page<SysLogOperation>> Get(KeywordRequest request);
        Task Post(SysLogOperation request);
    }
}
